package com.example.prison.config;

public class StringUtil {

    /**
     * 将整数转为指定长度的byte数组
     * @param value
     * @param byteLength
     * @return
     */
    public static byte[] intToBytesArray(int value, int byteLength) {
        byte[] bytes = new byte[byteLength];
        for (int i = 0; i < byteLength; i++) {
            bytes[byteLength - 1 - i] = (byte) (value >> (i * 8));
        }
        return bytes;
    }

    /**将byte类型数组转化成Ascii字符串
     * @param b
     * @return
     */
    public static String byteToPrintAsciiHexString(byte[] b) {
        String res = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            res += hex;
        }

        return res;
    }


    /**将byte类型数组转化成16进制字符串
     * @param src byte类型数组
     * @return
     */
    public static String bytesTo16HexString(byte[] src) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                sb.append(0);
            }
            sb.append(hv);
        }
        return sb.toString();
    }

    /**
     * Ascii转String
     * @param result2
     * @return
     */
    public static String AsciiToString(byte[] result2) {
        StringBuilder sbu = new StringBuilder();
        for (byte b : result2) {
            if (0 == b) {
                break;
            }
            sbu.append((char) Integer.parseInt(String.valueOf(b)));
        }
        return sbu.toString();
    }

    /**
     * 长度小于4的byte数组转换为int,大于只取低4字节或byte数组长度
     * @param bytes
     * @return
     */
    public static int bytesToInt(byte[] bytes) {
        int value = 0;
        int length = Math.min(bytes.length, 4); // 只取低4字节或byte数组长度
        for (int i = 0; i < length; i++) {
            value = (value << 8) | (bytes[bytes.length - length + i] & 0xFF);
        }
        return value;
    }

}
